package com.changan.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.changan.entity.User;
import com.changan.exception.BusinessException;
import com.changan.mapper.UserMapper;
import com.changan.response.ResultCode;
import com.changan.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.changan.utils.JWTUtils;
import com.changan.utils.MD5Utils;
import com.changan.vo.UserVO;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author NieChangan
 * @since 2022-12-13
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public Page<User> selectUserByPage(Page<User> page, UserVO userVO) {
        //这是多表联查返回的结果,但是这个结果如何分页呢?
        List<User> userList = this.baseMapper.getUserByPage(page, userVO);
        page.setRecords(userList);
        return page;
    }

    @Override
    public List<User> selectUserList(UserVO userVO) {
        List<User> userList = this.baseMapper.getUserList(userVO);
        return userList;
    }

    @Override
    public void exportUserExcel(HttpServletResponse response, List<User> userList) throws IOException {

        //----- 写入excel文件
        String exportFileName = "TbUserInfo.xlsx";
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.ms-excel");
        response.addHeader("Content-Disposition", "attachment;filename=" + exportFileName);
        EasyExcel.write(response.getOutputStream(), User.class)
                .sheet("用户信息")
                //自动列宽
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .doWrite(userList);
    }

    @Override
    public String login(String username, String password) {
        String token = null;
        //先根据用户名查询用户信息
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        //构造查询的条件
        wrapper.eq(StringUtils.isNotEmpty(username),User::getUsername,username);
        User user = this.baseMapper.selectOne(wrapper);
        if(user!=null){
            //说明能在数据库中找到该用户
            //获取到当前登录username对应的盐
            String salt = user.getSalt();
            //获取到数据库中加密的密码
            String encryptPassword = user.getPassword();
            //需要对传过来的原始密码进行加盐处理
            String md5Encryption = MD5Utils.md5Encryption(password, salt);
            //加盐成功之后得到加密加盐的密码,跟encryptPassword进行比较,看是否相同
            if(!encryptPassword.equals(md5Encryption)){
                throw new BusinessException(ResultCode.USER_CREDENTIALS_ERROR.getCode(),
                        ResultCode.USER_CREDENTIALS_ERROR.getMessage());
            }else{
                //生成jwt
                token = JWTUtils.sign(username, md5Encryption);
            }
        }else{
            //errCode  errMsg
            throw new BusinessException(ResultCode.USER_ACCOUNT_NOT_EXIST.getCode(),
                    ResultCode.USER_ACCOUNT_NOT_EXIST.getMessage());
        }
        return token;
    }
}
